//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by 上官风雨 on 15/11/10.
//  Copyright © 2015年 上官风雨. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    var account :UserAccount?
    
    //获取令牌
    var token :String? {
        
        return account?.access_token
    }
    
    //用户是否登录
    var userLogin : Bool {
        
        return account?.access_token != nil
        
    }
    //用户名字
    var userName :String?{
        
        return account?.name
    }
    var imageURL :NSURL?{
    
        return NSURL(string: account?.avatar_large ?? "")
    }
    
    
    //获取用户信息
    override init() {
        
        account = UserAccount.loadAccount()
        
      
    }

    
    //加载用户令牌
    func loadAccessToken (code : String,finished:(error:NSError?)->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let pramaters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code": code,"redirect_uri":redirect_uri]
        
        let tool = NetworkTools.tools
        
        tool.requestJsonDict(.Post, urlString: urlString, parameters: pramaters) { (result, error) -> () in
            
            
            if error != nil {
                
                finished(error: error)
                return
            }
                
            let account = UserAccount(dict: result!)
            
            self.loadUserInfo(account,finished: finished)
            
        }
        

        
    }
    //通过令牌加载用户信息
    private func loadUserInfo (account:UserAccount,finished:(error : NSError?) ->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let perameters = ["access_token":account.access_token!,"uid":account.uid!]
        
        let tool = NetworkTools.tools
        
        tool.requestJsonDict(.Get, urlString: urlString, parameters: perameters) { (result, error) -> () in
            
            if error != nil {
                
                finished(error: error)
                return
            }
            
            account.avatar_large = result!["avatar_large"] as? String
            account.name = result!["name"] as? String
            
            account.saveAccount()
            
            finished(error: error)
            
        }
        

    }

    

}
